import numpy as np
import cv2
import matplotlib.pyplot as plt


def piecewise_linear(x, breakpoints, slopes):
    return np.piecewise(x, [x < breakpoints[0], (x >= breakpoints[0]) & (x < breakpoints[1]), x >= breakpoints[1]],
                        [lambda x: slopes[0] * x,
                         lambda x: slopes[1] * (x - breakpoints[0]) + slopes[0] * breakpoints[0],
                         lambda x: slopes[2] * (x - breakpoints[1]) + slopes[1] * (breakpoints[1] - breakpoints[0]) +
                                   slopes[0] * breakpoints[0]])


def reverse_function(x):
    return -x + 255


def log_transform(x, c):
    return c * np.log1p(np.abs(x))


def linear_transform(img, breakpoints, slopes):
    # 将图像转换为灰度图像
    if len(img.shape) == 3:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 对每个像素应用分段线性变换
    # transformed_img = piecewise_linear(img, breakpoints, slopes)
    # transformed_img = reverse_function(img)
    transformed_img = log_transform(img, c=5)

    return transformed_img.astype(np.uint8)


# 加载灰度图像
image = cv2.imread('./shizi.png', cv2.IMREAD_GRAYSCALE)

# 定义分段函数的分段点和斜率
breakpoints = [100, 150]  # 分段点
slopes = [0.5, 2, 1]  # 斜率

# 应用线性变换
transformed_image = linear_transform(image, breakpoints, slopes)

# 显示原始图像
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.show()

# 显示处理后的图像
plt.imshow(transformed_image, cmap='gray')
plt.title('Transformed Image')
plt.axis('off')
plt.show()
